package com.asia5b.a5mall.member.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.adapter.CollectAdapter
import com.asia5b.a5mall.member.databinding.FragmentCollectBinding
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.event.CollectGoodsChange
import com.asia5b.a5mall.middleware.logic.viewmodel.member.CollectFragmentVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.fragment_collect.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2019/12/20.
 */
class CollectFragment : SimpleFragment<CollectFragmentVM, FragmentCollectBinding>() {
    override val viewModelClazz: Class<CollectFragmentVM>
        get() = CollectFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentCollectBinding {
        return FragmentCollectBinding.inflate(layoutInflater, container, false)
    }


    var type: Int = 0

    val mDatas = arrayListOf<MultiItemEntity>()
    val mAdapter by lazy { CollectAdapter(mDatas) }
    val mRecyclerView by lazy { rv_collect }
    var isShowDelete = false

    val emptyView by lazy { newEmptyView(mActivity) }


    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoCollect
        mDataBinding.autoCollect.setEnableRefresh(false)
        if(arguments!=null) {
            type = requireArguments().getInt("type")
        }
        setEditStateView()
        mRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = mAdapter
            addItemDecoration(newDivider(mActivity))
        }
    }

    fun setEditStateView() {
        head_collect.setRithtText((isShowDelete).judge(R.string.完成, R.string.编辑))
        mDataBinding.isShowDelete = isShowDelete
        mAdapter.isShowDelete = isShowDelete
        mAdapter.notifyDataSetChanged()
    }

    fun setCheckAllView() {
        var checkAll = true
        for (itemEntity in mDatas) {
            if (itemEntity is AbsGoodsModel) {
                if (checkAll) {
                    checkAll = itemEntity.absGoodsCheckedOb.get()
                }
            }
            if (itemEntity is AbsShopModel) {
                if (checkAll) {
                    checkAll = itemEntity.checkOB.get()
                }
            }
            if (!checkAll) {
                break
            }
        }
        cb_collect_checkall.isChecked = checkAll

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        getDatas(2)
    }

    override fun startObserver() {
        mViewModel.getGoodsCollectListResultLiveData.observe(this, Observer {
            getGoodsCollectListResult(it)
        })
        mViewModel.getShopCollectListResultLiveData.observe(this, Observer {
            getShopCollectListResult(it)
        })
        mViewModel.deleteCollectionsResultLiveData.observe(this, Observer {
            deleteCollectionsResult(it)
        })
        mViewModel.deleteCollectionShopListResultLiveData.observe(this, Observer {
            deleteCollectionShopListResult(it)
        })
    }

    override fun initEvent() {


        head_collect.setTitleName((type == 0).judge(R.string.商品关注, R.string.店铺关注))
        head_collect.setRightClickListener {
            isShowDelete = !isShowDelete
            setEditStateView()
        }
        cb_collect_checkall.setOnClickListener {
            for (itemEntity in mDatas) {
                if (itemEntity is AbsGoodsModel) {
                    itemEntity.absGoodsCheckedOb.set(cb_collect_checkall.isChecked)
                }
                if (itemEntity is AbsShopModel) {
                    itemEntity.checkOB.set(cb_collect_checkall.isChecked)
                }
            }
            setCheckAllView()
            mAdapter.notifyDataSetChanged()
        }
        bt_collect_delete.setOnClickListener {
            val list = arrayListOf<Int>()
            for (itemEntity in mDatas) {
                if (itemEntity is AbsGoodsModel) {
                    if (itemEntity.absGoodsCheckedOb.get()) {
                        list.add(itemEntity.absGoodsId)
                    }
                }
                if (itemEntity is AbsShopModel) {
                    if (itemEntity.checkOB.get()) {
                        list.add(itemEntity.absShopId)
                    }
                }
            }
            if (list.size == 0) {
                showMessage(getString(R.string.尚未选择商品))
            } else {
                CancelSureViewModel(mActivity).apply {
                    contentStringRes = R.string.是否需要删除选中商品
                    rightClick = {
                        if (type == 0) {
                            mViewModel.deleteCollections(list)
                        } else {
                            mViewModel.deleteCollectionShopList(list)
                        }
                    }
                }.show()
            }
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.getId()) {
                R.id.iv_collect_addcart -> {
                    val item = mAdapter.getItem(position) as AbsGoodsModel
                    val bundel = Bundle()
                    bundel.putBoolean("type", true)
                    bundel.putSerializable("data", item)
                    bundel.putInt("goodsId", item.absGoodsId)
                    val dialog = ARouter.getInstance().build(ActCons.GoodsSpecDF).with(bundel).navigation()
                    if (dialog != null && dialog is DialogFragment) {
                        dialog.show(childFragmentManager, "GoodsSpecDF")
                    }
                }
                R.id.cb_collect_goods_check,
                R.id.cb_collect_shop_check -> {
                    setCheckAllView()
                }
                R.id.cons_collec_goods_gen -> {
                    val model = mAdapter.getItem(position) as AbsGoodsModel
                    startGoodsDetailActivity(mActivity, model.absGoodsId)
                }
                R.id.tv_collect_goods_delete -> {
                    val model = mAdapter.getItem(position) as AbsGoodsModel
                    CancelSureViewModel(mActivity, R.string.是否需要删除选中商品) {
                        mViewModel.deleteCollections(arrayListOf(model.absGoodsId))
                    }.show()
                }
                R.id.cons_collect_shop_gen -> {
                    val model = mAdapter.getItem(position) as AbsShopModel
                    startShopActivity(mActivity, model.absShopId)
                }
                R.id.tv_collect_shop_delete -> {
                    val model = mAdapter.getItem(position) as AbsShopModel
                    CancelSureViewModel(mActivity, R.string.是否需要删除选中商品) {
                        mViewModel.deleteCollectionShopList(arrayListOf(model.absShopId))
                    }.show()
                }
            }
        }
    }

    override fun lazyFetchData() {
        getDatas(0)
    }

    fun getDatas(refresh: Int) {
        mViewModel.getDatas(refresh, type)
    }

    fun getGoodsCollectListResult(resultModel: ResultModel<ArrayList<AbsGoodsModel>>) {
        if (emptyView.parent == null) {
            mAdapter.setEmptyView(emptyView)
        }
        if (resultModel.page == 1) {
            mDatas.clear()
        }
        if (!resultModel.data.isNullOrEmpty()) {
            mAdapter.addData(resultModel.data!!)
        }
        mDataBinding.autoCollect.setEnableLoadMore(resultModel.page < resultModel.sumPage)
    }

    fun getShopCollectListResult(resultModel: ResultModel<ArrayList<AbsShopModel>>) {
        if (emptyView.parent == null) {
            mAdapter.setEmptyView(emptyView)
        }
        if (resultModel.page == 1) {
            mDatas.clear()
        }
        if (!resultModel.data.isNullOrEmpty()) {
            mAdapter.addData(resultModel.data!!)
        }
        mDataBinding.autoCollect.setEnableLoadMore(resultModel.page < resultModel.sumPage)
    }

    fun deleteCollectionShopListResult(ids: ArrayList<Int>) {
        val iterator = mDatas.iterator()
        while (iterator.hasNext()) {
            val model = iterator.next() as AbsShopModel
            if (ids.contains(model.absShopId)) {
                iterator.remove()
            }
        }
        mAdapter.notifyDataSetChanged()
        setCheckAllView()
        getEventBus().post(CollectGoodsChange(javaClass.simpleName))
    }

    fun deleteCollectionsResult(ids: ArrayList<Int>) {

        val iterator = mDatas.iterator()
        while (iterator.hasNext()) {
            val model = iterator.next() as AbsGoodsModel
            if (ids.contains(model.absGoodsId)) {
                iterator.remove()
            }
        }
        mAdapter.notifyDataSetChanged()
        setCheckAllView()
        getEventBus().post(CollectGoodsChange(javaClass.simpleName))
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCollectGoodsChange(event: CollectGoodsChange) {
        if (!TextUtils.equals(javaClass.simpleName, event.tag)) {
            getDatas(1)
        }
    }
}